<?php
// register.php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    if ($password !== $confirm_password) {
        echo '密码和确认密码不匹配。';
        exit();
    }

    $db = new PDO('sqlite:users.db');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 检查用户名是否已存在
    $query = $db->prepare("SELECT id FROM users WHERE username = :username");
    $query->bindParam(':username', $username);
    $query->execute();

    if ($query->fetch(PDO::FETCH_ASSOC)) {
        echo '用户名已存在。';
        exit();
    }

    // 插入新用户
    $query = $db->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");
    $query->bindParam(':username', $username);
    $query->bindParam(':password', password_hash($password, PASSWORD_DEFAULT));
    
    if ($query->execute()) {
        echo '注册成功！';
    } else {
        echo '注册失败。';
    }
}
?>
